package com.chcit.mobile.mvp.receive.fragment.pack.child;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;

import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerScanPackageComponent;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.common.presenter.ScanPackagePresenter;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.receive.Entity.AsnPackageBean;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.jakewharton.rxbinding3.view.RxView;
import com.jakewharton.rxbinding3.widget.RxTextView;
import com.jess.arms.di.component.AppComponent;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.xuexiang.xui.widget.spinner.editspinner.SimpleAdapter;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;
import com.xuexiang.xui.widget.textview.label.LabelButtonView;
import com.xuexiang.xui.widget.toast.XToast;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.yokeyword.fragmentation.SupportFragment;

public class FirstPagerFragment extends ScanFragment<ScanPackagePresenter> implements ScanPackageContract.View {
    private static final int REQUEST_CODE_SCAN = 188 ;
    @BindView(R.id.tv_check_receive_packageNo)
    ValidatorEditText tvCheckReceivePackageNo;
    @BindView(R.id.tv_check_receive_productName)
    ValidatorEditText tvCheckReceiveProductName;
    @BindView(R.id.tv_check_receive_productCode)
    ValidatorEditText tvProductCode;
    @BindView(R.id.tv_check_receive_productSpec)
    ValidatorEditText tvCheckReceiveProductSpec;
    @BindView(R.id.tv_check_receive_manufacturer)
    ValidatorEditText tvCheckReceiveManufacturer;
    @BindView(R.id.tv_check_receive_qty)
    ValidatorEditText tvCheckReceiveQty;
    @BindView(R.id.tv_check_receive_lot)
    ValidatorEditText tvCheckReceiveLot;
    @BindView(R.id.tv_check_receive_guarenteeDate)
    ValidatorEditText tvCheckReceiveGuarenteeDate;
    @BindView(R.id.tv_check_receive_hint)
    Button btImage;
    @BindView(R.id.bt_check_receive_check)
    LabelButtonView lbvLeft;
    @BindView(R.id.bt_check_receive_belowStandard)
    LabelButtonView lbvRight;
    @BindView(R.id.img_check_receive_scan)
    AppCompatImageView imgScan;
    @BindView(R.id.spinner_receive_locator)
    EditSpinner spinnerLocaltor;
    @BindView(R.id.ll_receive_locator)
    LinearLayout llLocator;
    AsnPackageBean asnPackageBean;
    public final static int REQUEST_CODE = -8;
    private Badge badgeView;
    private Badge badgePackageNoView;
    private Disposable lbvRightDisposable;
    private MenuTypeEnum type;
    private Disposable lbvLeftDisposable;
    private Disposable tvPackageNoDisposable;
    private String regex ;
    Pattern pattern;
    private ZxingConfig config = null;

    public FirstPagerFragment(MenuTypeEnum type) {
        this.type = type;
    }

    public static Fragment newInstance(MenuTypeEnum type) {

        return new FirstPagerFragment(type);
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

        Matcher m=pattern.matcher(barcodeData);
        if(m.find()){
            queryData(barcodeData);
        }else{
            if(asnPackageBean != null&& lbvRight.isEnabled()){
                spinnerLocaltor.getEditText().requestFocus();
                hideSoftInput();
                spinnerLocaltor.getEditText().setText(barcodeData);
            }
        }

    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);

    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_check_receive_first, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        tvCheckReceiveProductName.addTextChangedListener(textWatcher);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        regex =prefs.getString("package_no_regex", "^(\\S{4})(\\d{14})");
        pattern=Pattern.compile(regex);
        if(badgePackageNoView==null){
            badgePackageNoView =new BadgeView(mContext)
                    .bindTarget(tvCheckReceivePackageNo)
                    .setBadgeGravity(Gravity.TOP|Gravity.END);
        }
        lbvRightDisposable = RxView.clicks(lbvRight)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switch (type){
                        case PACKAGE_PUTAWAY: //上架功能
                            doConfirmPutWayUp();
                            break;
                        case PACKAGE_CHECK: 
                            doRejectConfirmReceive();
                            break;
                    }

                });
        lbvLeftDisposable = RxView.clicks(lbvLeft)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switch (type){
                        case PACKAGE_PUTAWAY: //上架
                            doConfirmPutWayReject();
                            break;
                        case PACKAGE_CHECK:
                            inspecteConfirm();
                            break;
                    }

                });
       tvPackageNoDisposable = RxTextView.editorActionEvents(tvCheckReceivePackageNo)
                .subscribe(textViewEditorActionEvent -> {
                    String text = Objects.requireNonNull(tvCheckReceivePackageNo.getText()).toString();
                    if (textViewEditorActionEvent.getActionId() == KeyEvent.KEYCODE_ENDCALL&&!text.isEmpty()){
                        onBarcodeEventSuccess(text);
                    }
                });
        if(type.equals(MenuTypeEnum.PACKAGE_PUTAWAY)){
            lbvRight.setText("上架");
            lbvLeft.setText("取消验收");
            spinnerLocaltor.setEnabled(false);
            btImage.setVisibility(View.INVISIBLE);


        }else{
            llLocator.setVisibility(View.GONE);
        }

//        BadgeView badge = new BadgeView(mContext);
//        badge.bindTarget(btImage)
//                .setBadgeBackground(getResources().getDrawable(R.drawable.svg_flag))
//                .setBadgeGravity(Gravity.CENTER);

     //   badge.setBadgeBackground(getResources().getDrawable(R.drawable.svg_flag));


    }

    private void initSpinner() {
        JSONObject data = new JSONObject();
        data.put("productId", asnPackageBean.getProductId());
        data.put("showStorageLoc", "");
        assert mPresenter != null;
        if(asnPackageBean.getLocatorValue()!=null){
            spinnerLocaltor.setAdapter(new SimpleAdapter<>(mContext,Arrays.asList(new Locator(asnPackageBean.getLocatorValue()))))
                    .setTextColor(ResUtils.getColor(R.color.colorGreenPrimary))
                    .setTextSize(spinnerLocaltor.getEditText().getTextSize())
                    .setBackgroundSelector(R.drawable.selector_custom_spinner_bg);
            spinnerLocaltor.setText(asnPackageBean.getLocatorValue());
        }

//        mPresenter.getLocators(data, list -> {
//
//
//
//        });

    }

    private void setViewData() {
        if(asnPackageBean!=null){
            lbvRight.setLabelVisual(false);
            lbvLeft.setLabelVisual(false);
            badgePackageNoView.hide(false);
            lbvLeft.setEnabled(false);
            btImage.setEnabled(false);
            lbvRight.setEnabled(false);
//            spinnerLocaltor.setEnabled(false);
            if("Y".equals(asnPackageBean.getIsNeedInspecte())){
                lbvLeft.setLabelVisual(true);
                lbvLeft.setLabelText("需要");
            }
            if("Y".equals(asnPackageBean.getIsInspecte())){
                lbvLeft.setLabelVisual(true);
                lbvLeft.setLabelText("已开箱");
            }
            if("Y".equals(asnPackageBean.getIsColdStorage())){
                if(badgeView==null){
                    badgeView =  new BadgeView(mContext)
                            .bindTarget(btImage)
                            .setBadgeGravity(Gravity.TOP|Gravity.START);

                }
                badgeView.setBadgeNumber(asnPackageBean.getAttachmentCount());
                btImage.setEnabled(true);
            }

            tvCheckReceivePackageNo.setText(asnPackageBean.getPackageNo());
            tvCheckReceiveGuarenteeDate.setText(asnPackageBean.getGuaranteeDate());
            tvCheckReceiveLot.setText(asnPackageBean.getLot());
            tvCheckReceiveProductName.setText(asnPackageBean.getProductName());
            tvCheckReceiveQty.setText(asnPackageBean.getQtyText());
            tvCheckReceiveManufacturer.setText(asnPackageBean.getManufacturer());
            tvCheckReceiveProductSpec.setText(asnPackageBean.getProductSpec());
            tvProductCode.setText(asnPackageBean.getProductCode());

        }

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void killMyself() {
        if(lbvRightDisposable!=null){
            lbvRightDisposable.dispose();
        }
        if(lbvLeftDisposable!=null){
            lbvLeftDisposable.dispose();
        }
        if(tvPackageNoDisposable!=null){
            tvPackageNoDisposable.dispose();
        }
    }
    private void queryData(String scanCode){

        mPresenter.queryAsnPackageList(
                new QueryListInput.Builder()
//                                .asnId(String.valueOf(asnResultBean.getAsnId()))
                        .packageNo(scanCode)
                        .warehouseId(HttpClientHelper.getSelectWareHouse().getId())
//                        .checkStatus("N")
                        .build(),
                list -> {
                    if(list.size()>0){
                        asnPackageBean = list.get(0);
                        String asnName = "";
                        //alp.qtyChecked > 0 AND alp.qtyrejected = 0
                        switch (type){
                            case PACKAGE_CHECK:
                                if(asnPackageBean.getQtyChecked().intValue()>0&&asnPackageBean.getQtyRejected().intValue()==0){
                                    setViewData();
                                    badgePackageNoView.setBadgeText("已验收");
                                    lbvRight.setEnabled(true);
                                    lbvLeft.setEnabled(true);

                                }else if(asnPackageBean.getQtyRejected().compareTo(BigDecimal.ZERO)>0){
                                    setViewData();
                                    badgePackageNoView.setBadgeText("不合格");
                                    lbvRight.setLabelVisual(true);

                                }else if(asnPackageBean.getQtyChecked().intValue()==0&&asnPackageBean.getQtyRejected().intValue()==0){
                                     //待验收
                                    doConfirmReceive();
                                 }else{
                                     XToast.info(mContext,"包装不合法！").show();
                                }
                                break;
                            case PACKAGE_PUTAWAY:

                                if(asnPackageBean.getQtyPutawayed().compareTo(BigDecimal.ZERO)>0){
                                    setViewData();
                                    badgePackageNoView.setBadgeText("已上架");

                                }else if(asnPackageBean.getQtyChecked().intValue()>0&&asnPackageBean.getQtyPutawayed().intValue()==0){
                                    //待上架
                                    setViewData();
                                    spinnerLocaltor.setEnabled(true);
                                    initSpinner();
                                    lbvRight.setEnabled(true);
                                    lbvLeft.setEnabled(true);
                                    lbvLeft.setLabelVisual(false);
                                }else{
                                    XToast.info(mContext,"包装不合法！").show();
                                }

                                break;
                            default:
                                XToast.info(mContext,"没有查询到包装信息!").show();
                                return;
                        }
                        SecondPagerFragment secondPagerFragment = findFragment(SecondPagerFragment.class);
                        if(secondPagerFragment!=null){
                            secondPagerFragment.setCheckAsnPackageBean(asnPackageBean);
                        }
                    }
                }

        );
//        PageBean.Builder pageBuilder = new PageBean.Builder();
//        pageBuilder.limit(800000)
//                .start(0);
//        QueryListInput.Builder queryListInput =new  QueryListInput.Builder()
//                .page("check")
//                .asnType("PO");
//        queryListInput.asnNo(scanCode);

//        if (!tvDateFrom.getCenterString().isEmpty()) {
//            queryListInput.dateArrivedFrom(tvDateFrom.getCenterString());
//
//        }
//        if(!tvDateTo.getCenterString().isEmpty()){
//            queryListInput.dateArrivedTo(tvDateTo.getCenterString());
//        }
//        if (bpartnerBean != null && bpartnerBean.getId()!= 0) {
//            queryListInput.bpartnerId((long)bpartnerBean.getId());
//        }
//        queryListInput.warehouseId(HttpClientHelper.getSelectWareHouse().getId());
//        mPresenter.getListData(pageBuilder.build(),queryListInput.build(),result->{
//            if(result.size()>0){
//                asnResultBean = result.get(0);
//            }
//
//        });

    }
    //验收确认方法调用
    private void doConfirmReceive() {
        JSONObject param = new JSONObject();
        JSONArray packageNos = new JSONArray();
        packageNos.add(asnPackageBean.getPackageNo());
        param.put("asnId", asnPackageBean.getAsnId());//
        param.put("packageNo", packageNos);
        mPresenter.checkAsnPackageRecieve(param, () -> {
            XToast.success(mContext, "验收成功！").show();
            setViewData();
            badgePackageNoView.setBadgeText("已验收");
            lbvRight.setEnabled(true);
            lbvLeft.setEnabled(true);
            if("Y".equals(asnPackageBean.getIsColdStorage())){
                btImage.setEnabled(true);
            }

        });
    }
    //上架确认方法调用
    private void doConfirmPutWayUp() {
        JSONObject param = new JSONObject();
        JSONArray packageNos = new JSONArray();
        packageNos.add(asnPackageBean.getPackageNo());
        param.put("asnId", asnPackageBean.getAsnId());//
        param.put("packageNo", packageNos);
        if(StringUtils.isEmpty(spinnerLocaltor.getText())){
            XToast.warning(mContext,"货位不能为空！").show();
            return;
        }
        param.put("locatorValue", spinnerLocaltor.getText());
        mPresenter.pickupAsnPackageRecieve(param, () -> {
            XToast.success(mContext, "上架成功！").show();
            badgePackageNoView.setBadgeText("已上架");
            lbvRight.setEnabled(false);
            lbvLeft.setEnabled(false);
//            if("Y".equals(asnPackageBean.getIsColdStorage())){
//                btImage.setEnabled(true);
//            }

        });
    }

    //取消上架
    private void doConfirmPutWayReject() {

        mPresenter.reCheckTaskLine(Arrays.asList(asnPackageBean.getPackageNo()),asnPackageBean.getAsnId(), () -> {
            badgePackageNoView.hide(true);
            XToast.success(mContext, "操作成功！").show();
            lbvLeft.setText("已取消");
            lbvLeft.setLabelVisual(true);
            lbvRight.setEnabled(false);
        });
    }
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);

    }

    //验收场合拒收方法调用
    private void doRejectConfirmReceive() {
        mPresenter.queryListData(new Consumer<List<Statu>>() {
            int i = 0;

            @Override
            public void accept(List<Statu> status) throws Exception {
                new MaterialDialog.Builder(mContext)
                        .title("拒收原因")
                        .items(status)
                        .itemsCallbackSingleChoice(i, (dialog, itemView, which, text) -> {
                            i = which;
                            // {asnId:"1212",asnLineId:12123,rejectReason:"test",packageNo:["2323","232323dfdf"]}}
                            // JSONObject data = new JSONObject();
                            JSONObject param = new JSONObject();
                            JSONArray packageNos = new JSONArray();
                            packageNos.add(asnPackageBean.getPackageNo());
                            param.put("asnId", asnPackageBean.getAsnId());//
                            param.put("packageNo", packageNos);
                            param.put("rejectReason", status.get(i).getId());
                            if("其他".equals(text)){
                                new MaterialDialog.Builder(mContext)
                                        .title("其他原因")
                                        .autoDismiss(false)
                                        .input(
                                                "",
                                                "",
                                                false,
                                                ((resonDialog, input) -> {
//                                                    XToast.info(mContext,input).show();
                                                    param.put("description",input);
                                                    mPresenter.rejectAsnPackage(param, () -> {
                                                        resonDialog.dismiss();
                                                        dialog.dismiss();
                                                        badgePackageNoView.hide(true);
                                                        lbvRight.setLabelVisual(true);
                                                        lbvRight.setEnabled(false);
                                                        XToast.success(mContext, "操作成功！").show();

                                                    });

                                                }))
                                        .positiveText("确认")
                                        .negativeText("取消")
                                        .onNegative(((resonDialog, select) -> {
                                            resonDialog.dismiss();

                                        }))
                                        .cancelable(false)
                                        .show();
                                return false;
                            }
                            mPresenter.rejectAsnPackage(param, () -> {
                                dialog.dismiss();
                                badgePackageNoView.hide(true);
                                XToast.success(mContext, "操作成功！").show();
                                lbvRight.setLabelVisual(true);
                                lbvRight.setEnabled(false);
                            });
                            return true;
                        }).neutralText("取消")
                        .positiveText("确认")
                        .onNeutral((d,i)->{
                            d.dismiss();
                        })
                        .autoDismiss(false)
                        .cancelable(false)
                        .build()
                        .show();
            }
        });
    }
    //开箱验视确认方法调用
    private void inspecteConfirm() {
        JSONObject data = new JSONObject();
        JSONArray packageNos = new JSONArray();
        packageNos.add(asnPackageBean.getPackageNo());
        data.put("packageNo", packageNos);
        // {asnId:"1212",asnLineId:12123,locatorId:"1212",packageNo:["2323","232323dfdf"]}
        data.put("asnId",asnPackageBean.getAsnId());
        assert mPresenter != null;
        mPresenter.inspectePackageRecieve(data, () -> {
            XToast.success(mContext, "验视成功！").show();
            lbvLeft.setLabelText("已开箱");
            lbvLeft.setLabelVisual(true);
            lbvLeft.setEnabled(false);
        });
    }

    @OnClick({R.id.tv_check_receive_hint,R.id.img_check_receive_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_check_receive_hint:
                ((SupportFragment) getParentFragment()).startForResult(ImagePickFragment.newInstance(asnPackageBean,type),REQUEST_CODE);
                //selectIcon();
                break;
            case R.id.img_check_receive_scan:
                Intent intent = new Intent(mContext, CaptureActivity.class);
                /*ZxingConfig是配置类
                 *可以设置是否显示底部布局，闪光灯，相册，
                 * 是否播放提示音  震动
                 * 设置扫描框颜色等
                 * 也可以不传这个参数
                 * */
                if(config==null){
                    config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                    config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
                    config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                    config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
                    config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                }
                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        int mEditTextHaveInputCount = 0 ;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    lbvRight.setEnabled(false);
                    lbvLeft.setEnabled(false);
                    btImage.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {


                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                onBarcodeEventSuccess(content);
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE&&resultCode == RESULT_OK&&data!=null ) {
            badgeView.setBadgeNumber(data.getInt(DataKeys.ATTACHMENT_COUNT.name()));
        }
    }
}
